/**
 * 
 */
package br.edu.ufcg.embedded.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import br.embedded.socialapp.data.FriendshipDAO;

/**
 * @author daniel
 *
 */
public class FileConsumer extends Thread
{
	private String directory;
	private String fileExtension;
	
	private boolean producerHasFinished;
	
	public FileConsumer(String directory, String fileExtension)
	{
		this.directory = directory;
		this.fileExtension = fileExtension;
		this.producerHasFinished = false;
	}
	
	@Override
	public void run()
	{
		consume();
	}
	
	private void consume()
	{
		System.out.println("FileConsumer is running...");
		
		while (!producerHasFinished)
		{			
			List<String> files = getFiles();

			if (files.size() > 0)
				FriendshipDAO.getInstance().bulkInsert(files);
		}
		
		List<String> files = getFiles();
		
		if (files.size() > 0)
			FriendshipDAO.getInstance().bulkInsert(files);
		
		System.out.println("FileConsumer has finished.");
	}
	
	private List<String> getFiles()
	{
		File f = new File(directory);

		String[] list = f.list();
		
		List<String> files = new ArrayList<String>();

		for (String file : list)
		{
			if (file.endsWith(fileExtension))
				files.add(directory + file);
		}
		
		return files;
	}
	
	public void producerFinished()
	{
		producerHasFinished = true;
	}
}
